package com.tcsl.exercise.demo.service.impl;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.tcsl.exercise.demo.constants.ResultEnum;
import com.tcsl.exercise.demo.dao.ItemMapper;
import com.tcsl.exercise.demo.entity.ItemEntity;
import com.tcsl.exercise.demo.entity.ItemSizeCa;
import com.tcsl.exercise.demo.entity.Page;
import com.tcsl.exercise.demo.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    ItemMapper itemMapper;

    @Override
    public List<ItemEntity> selectOne(Integer curr, Integer pageSize,String keyWord) {
        List<ItemEntity> itemEntities = itemMapper.selectPage(curr, pageSize, keyWord);
        System.out.println(itemEntities);
        return itemEntities;

    }

    @Override
    public List<ItemSizeCa> selectItemCa() {
        return itemMapper.selectAllItemCA();
    }

    public synchronized ResultEnum addItem(ItemEntity itemEntity){
        if (ObjectUtils.isEmpty(itemEntity)){
            return ResultEnum.FAIL;
        }
        ItemEntity nameEntity = new ItemEntity();
        nameEntity.setName(itemEntity.getName());
        List<ItemEntity> itemEntities = itemMapper.selectByElem(nameEntity,null);

        if (itemEntities != null && itemEntities.size() !=0){
            return ResultEnum.NAME_UNIQUE;
        }
        ItemEntity idEntity = new ItemEntity();
        idEntity.setId(itemEntity.getId());
        List<ItemEntity> idList = itemMapper.selectByElem(idEntity,null);
        if (idList != null && idList.size() !=0){
            return ResultEnum.ID_UNIQUE;
        }
        int i = itemMapper.addItem(itemEntity);
        return ResultEnum.SUCCESS;
    }

    @Override
    public int deleteById(Long id) {
        int i = itemMapper.deleteById(id);
        return i;
    }

    @Override
    public int selectByName(String name) {
        return 0;
    }

    @Override
    public int selectById(Long id) {
        return 0;
    }

    @Override
    public synchronized ResultEnum editItemById(ItemEntity itemEntity) {
        List<ItemEntity> itemEntities = itemMapper.selectByNameExId(itemEntity);
        if (itemEntities != null && itemEntities.size() != 0){
            return ResultEnum.NAME_UNIQUE;
        }
        int i = itemMapper.updateById(itemEntity);
        return ResultEnum.SUCCESS;
    }

    @Override
    public int selectItemCount(String keyWord) {
        ItemEntity itemEntity = new ItemEntity();
        List<ItemEntity> itemEntities = itemMapper.selectByElem(itemEntity, keyWord);
        if (itemEntities !=null)
        return itemEntities.size();
        return 0;
    }
}
